package qj.util.io;

import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;

public class ConvertTo7BitsReader extends Reader {
	
	private InputStream in;
	
	public int read(char[] cbuf, int off, int len) throws IOException {
		int i = 0;
		try {
			for (; i < len; i++) {
				cbuf[off + i] = read1();
			}
		} catch (EOFException e) {
			if (i==0)
				return -1;
		}
		return i;
	}
	
	private int index = 0;
	private byte[] buffer = new byte[8];
	private int read = 0;
	private char read1() throws IOException {
		if (index>=read) {
			index = 0;
			readMore();
		}
		return (char) buffer[index++];
	}

	private byte[] buffer2 = new byte[7];
	private void readMore() throws IOException {
        int read;
        if ((read=in.read(buffer2, 0, 7)) > -1) {
        	buffer[0] = getHeadByte(buffer2, read);
        	clearHeadBits(buffer2);
        	for (int i = 0; i < read; i++) {
        		buffer[i + 1] = buffer2[i];
			}
            this.read = read + 1;
        } else {
            this.read = -1;
        	throw new EOFException("End of input stream");
        }
	}

	private static void clearHeadBits(byte[] buffer) {
		for (int i = 0; i < buffer.length; i++) {
			if (buffer[i] < 0)
				buffer[i] += 128;
		}
	}

	private static byte getHeadByte(byte[] buffer, int read) {
		byte ret = 0;
		byte start = 64;
		for (int i = 0; i < read; i++) {
			if (buffer[i] < 0) {
				ret += start;
			}
			start/=2;
		}
		return ret;
	}

	public void close() throws IOException {
		if (in!=null)
			in.close();
	}
	
	public ConvertTo7BitsReader(InputStream in) {
		super();
		this.in = in;
	}
}
